package com.zyp.jobseeker.controller;

import com.zyp.jobseeker.entity.User;
import com.zyp.jobseeker.enums.UserRole;
import com.zyp.jobseeker.enums.UserStatus;
import com.zyp.jobseeker.utils.JwtUtil;
import com.zyp.jobseeker.utils.ResultUtil;
import com.zyp.jobseeker.service.AdminService;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/admin")
@PreAuthorize("hasAuthority('ADMIN')")  // 管理员权限
public class AdminController {

    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Autowired
    private AdminService adminService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 获取待审核学生列表
     */
    @GetMapping("/audit/students/pending")
    public ResultUtil<PageInfo<Map<String, Object>>> getPendingStudents(
            @RequestHeader("Authorization") String token,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            // 验证token有效性
            if (token == null || !token.startsWith("Bearer ")) {
                logger.warn("[管理员审核] 未提供有效的认证信息");
                return ResultUtil.fail(401, "未提供有效的认证信息");
            }
            token = token.substring(7);
            if (jwtUtil.isTokenExpired(token)) {
                logger.warn("[管理员审核] 认证信息已过期");
                return ResultUtil.fail(401, "认证信息已过期，请重新登录");
            }

            // 提取管理员信息
            Long adminId = jwtUtil.getUserIdFromToken(token);
            String userRole = UserRole.getByCode(jwtUtil.getRoleFromToken(token)).getDesc();

            logger.info("[管理员审核] 收到待审核学生查询请求，参数：page={}, size={}, adminId={}, role={}",
                    page, size, adminId, userRole);
            // 调用原始service方法获取User类型数据
            PageInfo<User> userPageInfo = adminService.getPendingStudents(page, size);

            // 转换为Map结构
            PageInfo<Map<String, Object>> mapPageInfo = convertToMapPageInfo(userPageInfo);
            logger.info("[管理员审核] 待审核学生查询完成，返回结果数: {}", mapPageInfo.getTotal());
            return ResultUtil.success("获取待审核学生列表成功", mapPageInfo);

        } catch (Exception e) {
            logger.error("[管理员审核] 待审核学生查询失败", e);
            return ResultUtil.fail(500, "获取待审核学生列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取待审核企业列表
     */
    @GetMapping("/audit/enterprises/pending")
    public ResultUtil<PageInfo<Map<String, Object>>> getPendingEnterprises(
            @RequestHeader("Authorization") String token,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            // 验证token有效性
            if (token == null || !token.startsWith("Bearer ")) {
                logger.warn("[管理员审核] 未提供有效的认证信息");
                return ResultUtil.fail(401, "未提供有效的认证信息");
            }
            token = token.substring(7);
            if (jwtUtil.isTokenExpired(token)) {
                logger.warn("[管理员审核] 认证信息已过期");
                return ResultUtil.fail(401, "认证信息已过期，请重新登录");
            }

            // 提取管理员信息
            Long adminId = jwtUtil.getUserIdFromToken(token);
            String userRole = UserRole.getByCode(jwtUtil.getRoleFromToken(token)).getDesc();

            logger.info("[管理员审核] 收到待审核企业查询请求，参数：page={}, size={}, adminId={}, role={}",
                    page, size, adminId, userRole);

            // 调用原始service方法获取User类型数据
            PageInfo<User> userPageInfo = adminService.getPendingEnterprises(page, size);

            // 转换为Map结构
            PageInfo<Map<String, Object>> mapPageInfo = convertToMapPageInfo(userPageInfo);

            logger.info("[管理员审核] 待审核企业列表转换完成，返回结果数: {}", mapPageInfo.getTotal());
            return ResultUtil.success(mapPageInfo);

        } catch (Exception e) {
            logger.error("[管理员审核] 待审核企业查询失败", e);
            return ResultUtil.fail(500, "获取待审核企业列表失败: " + e.getMessage());
        }
    }

    /**
     * 审核用户注册申请
     */
    @PutMapping("/audit/{userId}")
    public ResultUtil<String> auditUserRegistration(
            @RequestHeader("Authorization") String token,
            @PathVariable Long userId,
            @RequestBody Map<String, Object> requestBody) {
        try {
            // 验证token有效性
            if (token == null || !token.startsWith("Bearer ")) {
                logger.warn("[管理员审核] 未提供有效的认证信息");
                return ResultUtil.fail(401, "未提供有效的认证信息");
            }
            token = token.substring(7);
            if (jwtUtil.isTokenExpired(token)) {
                logger.warn("[管理员审核] 认证信息已过期");
                return ResultUtil.fail(401, "认证信息已过期，请重新登录");
            }

            // 提取管理员信息
            Long adminId = jwtUtil.getUserIdFromToken(token);
            String userRole = UserRole.getByCode(jwtUtil.getRoleFromToken(token)).getDesc();

            logger.info("[管理员审核] 收到用户审核请求，参数：userId={}, adminId={}, role={}",
                    userId, adminId, userRole);

            // 获取审核状态
            Integer userStatus = (Integer) requestBody.get("userStatus");
            if (userStatus == null ||
                    (userStatus != UserStatus.NORMAL.getCode() &&
                            userStatus != UserStatus.DISABLED.getCode())) {
                logger.warn("[管理员审核] 无效的审核状态: {}", userStatus);
                return ResultUtil.fail(400, "无效的审核状态");
            }

            // 执行审核操作
            boolean success = adminService.auditUserRegistration(userId, userStatus);
            if (success) {
                String statusDesc = UserStatus.getByCode(userStatus).getDesc();
                logger.info("[管理员审核] 用户审核完成，用户ID: {}, 状态: {}", userId, statusDesc);
                return ResultUtil.success("用户审核" + statusDesc);
            } else {
                return ResultUtil.fail(400, "用户审核失败");
            }

        } catch (Exception e) {
            logger.error("[管理员审核] 用户审核异常", e);
            return ResultUtil.fail(500, "用户审核失败: " + e.getMessage());
        }

    }
    // 获取所有求职申请
    @GetMapping("/applications")
    public ResultUtil<PageInfo<Map<String, Object>>> getAllApplications(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        PageInfo<Map<String, Object>> result = adminService.getAllApplications(page, size);
        return ResultUtil.success("查询成功", result);
    }

    // 获取所有面试邀请
    @GetMapping("/interviews")
    public ResultUtil<PageInfo<Map<String, Object>>> getAllInterviews(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        PageInfo<Map<String, Object>> result = adminService.getAllInterviews(page, size);
        return ResultUtil.success("查询成功", result);
    }
    /**
     * 将PageInfo<User>转换为PageInfo<Map<String, Object>>
     */
    private PageInfo<Map<String, Object>> convertToMapPageInfo(PageInfo<User> userPageInfo) {
        // 创建新的PageInfo并转换数据
        PageInfo<Map<String, Object>> mapPageInfo = new PageInfo<>();

        // 复制基础分页信息
        mapPageInfo.setPageNum(userPageInfo.getPageNum());
        mapPageInfo.setPageSize(userPageInfo.getPageSize());
        mapPageInfo.setSize(userPageInfo.getSize());
        mapPageInfo.setTotal(userPageInfo.getTotal());
        mapPageInfo.setPages(userPageInfo.getPages());

        // 复制导航页码信息
        mapPageInfo.setPrePage(userPageInfo.getPrePage());
        mapPageInfo.setNextPage(userPageInfo.getNextPage());
        mapPageInfo.setIsFirstPage(userPageInfo.isIsFirstPage());
        mapPageInfo.setIsLastPage(userPageInfo.isIsLastPage());
        mapPageInfo.setNavigatePages(userPageInfo.getNavigatePages());
        mapPageInfo.setNavigatepageNums(userPageInfo.getNavigatepageNums());

        // 转换用户数据
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (User user : userPageInfo.getList()) {
            Map<String, Object> userMap = new HashMap<>();
            userMap.put("id", user.getId());
            userMap.put("username", user.getUsername());
            userMap.put("role", user.getRole());
            userMap.put("status", user.getStatus());
            userMap.put("createTime", user.getCreateTime());
            mapList.add(userMap);
        }

        mapPageInfo.setList(mapList);
        return mapPageInfo;
    }
}